package.path = package.path .. ";/usr/local/share/lua/5.3/?.lua"
package.cpath = package.cpath .. ";/usr/local/lib/lua/5.3/?.so"
require('init')
local luasql = require('luasql.mysql')
local cjson = require("cjson")

--加载配置文件
local function load_config_file(filename)
    file = io.open(filename)
    if not file then
        error("open " .. filename .. " failed: " .. (err or "unknown error"))
        return
    end
    local content = file:read('*a')
    file:close()
    return cjson.decode(content)
end

local config = load_config_file("../config/config.json")

-- MySQL配置
local mysql_db = config.mysql_db
local mysql_username = config.mysql_username
local mysql_password = config.mysql_password
local mysql_host = config.mysql_host
local mysql_port = config.mysql_port

--创建环境对象
local env = luasql.mysql()

--连接数据库
local conn,err = env:connect(mysql_db,mysql_username,mysql_password,mysql_host,mysql_port)
if not conn then
    error("connect to database failed: " .. err)
    return
else
    print("connect mysql server success")
end

--设置数据库的编码格式
conn:execute("set names utf-8")

function register(username,password)
    local sql = string.format("select * from user_accounts where username = '%s'", username)
    local cur, error_msg = conn:execute(sql)

    if not cur then
        error("Failed to execute query: " .. error_msg)
    end

    local row = cur:fetch({}, "a")

    if not row then
        local insert_sql = string.format("insert into user_accounts (username,password) values ('" .. username.. "','" .. password .. "')")
        -- local insert_sql = string.format("insert into users (username,password) values ('" .. username.. "','" .. password .. "')")
        conn:execute(insert_sql)
        return true,"注册成功"
    else
        return false,"用户名已经存在"
    end
end


